package com.example.demofdfs.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

public abstract class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request,
			HttpServletResponse response) {
		logger.error(":" + request, ex);
		MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
		List<ObjectError> errors = c.getBindingResult().getAllErrors();
		StringBuffer errorMsg = new StringBuffer();
		errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
		pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString());
	}

	private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) {
		try {
			response.sendError(errorCode.value(), errorMessage);
		} catch (IOException e) {
			logger.error("failed to populate response error", e);
		}
	}
}
